﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using BYFW.DAL;
using System.Data;
using LDSP.Util;
using LDSP.Constants;

namespace LDSP.UI.EnterpriseAdmin
{
    public partial class MngCodification : LDSP.BRL.BaseEnterpriseAdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    this.CheckQS();
                }
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.BindTree();
                        this.InitTreeNodeSelection();
                        this.InitData();
                        this.BindGrid();
                    }
                    this.InitDataDynamicAfter();
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected string TitleName = "法律法规";
        protected string ShortTitleName = "法规";
        protected string ReferenceName = "发布文号";
        protected string TitleListName = "法规汇编";

        protected Catalog m_catalog = null;

        protected int LastID
        {
            get { return this.GetVSInt("LastID"); }
            set
            {
                this.SetVS("LastID", value);
                m_catalog = null;
            }
        }
        protected Catalog Catalog
        {
            get
            {
                if (m_catalog == null)
                {
                    m_catalog = new Catalog();
                    if (LastID != 0)
                    {
                        m_catalog.GetProperties(LastID);
                    }
                }
                return m_catalog;
            }
        }
        protected DocType DocType
        {
            get { return (DocType)this.GetVSInt("DocType"); }
            set
            {
                this.SetVS("DocType", (int)value);
            }
        }
        protected bool ShowAll
        {
            get { return this.GetVSBool("ShowAll"); }
            set { this.SetVS("ShowAll", value); }
        }

        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
            g_pageInfo.Direction = true;
            g_pageInfo.Sort = "name";
            g_pageInfo.PageSize = 10;
            g_pageInfo.PageIndex = this.grd_list.PageIndex;
        }
        protected void CheckQS()
        {
            int docType = this.GetInt(this.Request.QueryString["docType"]);
            docType = docType != 1 ? 0 : 1;
            DocType = (DocType)docType;
        }
        protected bool RB()
        {
            return true;
        }
        protected void InitData()
        {
            //不缓存则清空页面信息
            if (!needCachePageInfo)
            {
                g_pageInfo.ClearPageInfo();
            }
            this.GetCondition();
            this.SetSpecialPageInfo();
            this.BindDDLIsValid();
            this.JSShowModalDialog("", this.btn_addFavorite);
            this.JSShowModalDialog("", this.btn_addFavorite1);
        }
        protected void InitDataDynamicBefore()
        {
            ShowColumns();

            if (DocType == BRL.DocType.标准)
            {
                this.TitleName = "标准";
                this.ShortTitleName = "标准";
                this.ReferenceName = "标准号";
                this.TitleListName = "标准汇编";
                this.grd_list.Columns[5].Visible = true;
                this.grd_list.Columns[11].Visible = false;
            }
            this.grd_list.Columns[2].HeaderText = TitleName + "名称";
            this.grd_list.Columns[5].HeaderText = ReferenceName;
            this.grd_list.Columns[10].HeaderText = ShortTitleName + "概述";
            this.grd_list.Columns[12].HeaderText = this.LoginUser.Enterprise.EnterpriseConfig.ActionFieldName;
        }

        private void ShowColumns()
        {
            //法规需要显示的字段: 多选框，优先级，名称，       法规概述，关键条款，实施措施。
            //标准要显示的字段，  多选框，优先级，名称，标准号，标准概述，         实施措施。
            //this.grd_list.Columns[0].Visible = ShowAll;
            this.grd_list.Columns[1].Visible = ShowAll;
            //this.grd_list.Columns[2].Visible = ShowAll;
            this.grd_list.Columns[3].Visible = ShowAll;
            this.grd_list.Columns[4].Visible = ShowAll;
            this.grd_list.Columns[5].Visible = ShowAll;
            this.grd_list.Columns[6].Visible = ShowAll;
            this.grd_list.Columns[7].Visible = ShowAll;
            this.grd_list.Columns[8].Visible = ShowAll;
            this.grd_list.Columns[9].Visible = ShowAll;
            //this.grd_list.Columns[10].Visible = ShowAll;
            //this.grd_list.Columns[11].Visible = ShowAll;
            this.grd_list.Columns[12].Visible = ShowAll;
            this.grd_list.Columns[13].Visible = ShowAll;
            //this.grd_list.Columns[14].Visible = ShowAll;
        }
        protected void InitDataDynamicAfter()
        {
            this.JSSetDateTimeReadOnly(this.txt_releaseStartDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_releaseEndDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_implementStartDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_implementEndDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_uploadStartDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_uploadEndDT.ClientID);
        }
        protected void BindGrid()
        {
            DataTable dt = BYFW.SFL.CommonOP.SortedTable(new Codification().GetRecordsByEnterpriseIDForAllFavorite(LoginUser.EnterpriseID, g_pageInfo.ConditionWhere), g_pageInfo.GetSortExpression());

            this.grd_list.PageSize = g_pageInfo.PageSize;
            this.grd_list.PageIndex = g_pageInfo.PageIndex;
            this.grd_list.DataSource = dt;
            this.grd_list.DataBind();

            this.TotalRecords.Text = LDSP.Helper.StringUtil.GetSearchText(dt.Rows.Count);
        }
        protected void BindTree()
        {
            this.tre_obj.Nodes.Clear();

            TreeNode all = new TreeNode();
            all.Text = "所有";
            all.Value = "0";
            this.tre_obj.Nodes.Add(all);

            List<Catalog> rootCatalogs = new Catalog().GetListRootByDefault();
            for (int i = 0; i < rootCatalogs.Count; i++)
            {
                if (HaveCatalogPermission(rootCatalogs[i].ID))
                {
                    TreeNode nd = new TreeNode();
                    nd.Text = rootCatalogs[i].Name;
                    nd.Value = rootCatalogs[i].ID.ToString();
                    all.ChildNodes.Add(nd);
                    this.BindTreeAssis(nd, rootCatalogs[i].ID);
                }
            }
            all.CollapseAll();
        }
        protected void BindTreeAssis(TreeNode parent, int parentID)
        {
            List<Catalog> catalogs = new Catalog().GetListByParentID(parentID);
            for (int i = 0; i < catalogs.Count; i++)
            {
                if (HaveCatalogPermission(catalogs[i].ID))
                {
                    TreeNode nd = new TreeNode();
                    nd.Text = catalogs[i].Name;
                    nd.Value = catalogs[i].ID.ToString();
                    parent.ChildNodes.Add(nd);
                    this.BindTreeAssis(nd, catalogs[i].ID);
                }
            }
        }
        protected void InitTreeNodeSelection()
        {
            if (this.tre_obj.Nodes.Count > 0)
            {
                this.tre_obj.Nodes[0].Select();
                this.LastID = this.GetInt(this.tre_obj.SelectedValue);
            }
        }

        protected void BindDDLIsValid()
        {
            this.ddl_isValid.Items.Clear();
            this.ddl_isValid.Items.Add("--请选择--");
            this.ddl_isValid.Items.Add(new ListItem("无效", "0"));
            this.ddl_isValid.Items.Add(new ListItem("有效", "1"));
            try
            {
                this.ddl_isValid.SelectedIndex = 0;
            }
            catch { }

        }

        protected void GetCondition()
        {
            string cond = LastID == 0 ? string.Empty : DefaultDB.GetSQLNormalCondition("catalogID", EDataType.Int, LastID.ToString(), "=", true);
            cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("enterpriseID", EDataType.Int, "0", "=", true), true);
            cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("docType", EDataType.Int, ((int)DocType).ToString(), "=", true), true);
            if (this.txt_name.Text.Trim() != ""
                && this.txt_name.Text.Trim() != EmptySearch.value)
            {
                cond = this.AppendConditionMulti(cond, this.txt_name.Text.Trim(), "name", "Organization", "ReferenceNumber", "Summary", DocType == BRL.DocType.法律法规 ? "KeyItems" : "", "Action");
            }
            this.SetHighlight(this.txt_name.Text.Trim());
            if (this.ddl_isValid.SelectedIndex > 0)
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("isValid", EDataType.Bool, this.ddl_isValid.SelectedValue, "=", true), true);
            }
            if (this.txt_releaseStartDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("releaseDT", EDataType.Date, this.txt_releaseStartDT.Text, ">=", true), true);
            }
            if (this.txt_releaseEndDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("releaseDT", EDataType.Date, this.txt_releaseEndDT.Text, "<=", true), true);
            }
            if (this.txt_implementStartDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("implementDT", EDataType.Date, this.txt_implementStartDT.Text, ">=", true), true);
            }
            if (this.txt_implementEndDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("implementDT", EDataType.Date, this.txt_implementEndDT.Text, "<=", true), true);
            }
            if (this.txt_uploadStartDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("uploadDT", EDataType.Date, this.txt_uploadStartDT.Text, ">=", true), true);
            }
            if (this.txt_uploadEndDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("uploadDT", EDataType.Date, this.txt_uploadEndDT.Text, "<=", true), true);
            }
            g_pageInfo.Condition = cond;
        }

        private void JSShowModalDialog(string arg, WebControl ctrl)
        {
            this.JSShowDialog(string.Format("../Operation/AddFavoritePublicInfo.aspx?docType={0}&pageID={1}&{2}", ((int)DocType).ToString(), PageID, arg), 500, 400, ctrl, null, null, null, null, null, null, null, true, null, null, null, null, null);
        }

        protected void btn_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.GetCondition();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_export_Click(object sender, EventArgs e)
        {
            //Collect codifications.
            IDictionary<string, IList<Codification>> codifications = new Dictionary<string, IList<Codification>>();
            GridView grid = this.grd_list;
            for (int i = 0; i <= grid.Rows.Count - 1; i++)
            {
                CheckBox chb = (CheckBox)grid.Rows[i].FindControl("chb");
                if (chb.Checked)
                {
                    Codification ett = new Codification();
                    ett.GetProperties(this.GetInt(grid.DataKeys[i].Value));

                    if (ett.Catalog != null)
                    {
                        if (codifications.ContainsKey(ett.Catalog.Name))
                        {
                            codifications[ett.Catalog.Name].Add(ett);
                        }
                        else
                        {
                            IList<Codification> codificationList = new List<Codification>();
                            codificationList.Add(ett);

                            codifications.Add(ett.Catalog.Name, codificationList);
                        }
                    }
                }
            }

            CodificationExportBase<Catalog, Codification> export = null;
            string templateName = string.Empty;
            if (DocType == BRL.DocType.法律法规)
            {
                export = new CodificationExport();
                templateName = "finalCodification.xls";
            }
            else
            {
                export = new StandardExport();
                templateName = "finalStandard.xls";
            }

            //Get data table for codifications.
            IDictionary<string, DataTable> tables = new Dictionary<string, DataTable>();
            foreach (string key in codifications.Keys)
            {
                DataTable dt = export.ConstructDT(codifications[key]);
                tables.Add(key, dt);
            }

            //Export.
            export.Export(tables, Server, templateName);
        }
        protected void btn_addFavorite_Click(object sender, EventArgs e)
        {
            try
            {
                bool find = false;
                this.DoGirdChecked<Codification>(this.grd_list, "chb", delegate(Codification ett)
                {
                    find = true;
                    var tmp = new R_EnterpriseCodification();
                    //已存在的适用关系则不添加进去（处理并发情况）
                    if (!tmp.Exist(LoginUser.EnterpriseID, ett.ID))
                    {
                        tmp.DocID = ett.ID;
                        tmp.EnterpriseID = LoginUser.EnterpriseID;
                        tmp.FavoriteDT = DateTime.Now;
                        PublicFavoriteInfo pi = this.PublicFavoriteInfo(this.PageID);
                        tmp.Comment = pi.Comment;
                        tmp.Principal = pi.Principal;
                        tmp.Priority = pi.Priority;
                        tmp.Name = ett.Summary;
                        tmp.KeyItems = ett.KeyItems;
                        tmp.Action = ett.Action;
                        tmp.Add();
                    }
                });
                this.PublicFavoriteInfo(PageID, null, true);
                if (find)
                {
                    this.BindGrid();
                    this.JSAlert("添加适用成功！");
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_showAll_Click(object sender, EventArgs e)
        {
            ShowAll = !ShowAll;
            this.btn_showAll.Text = ShowAll ? "显示精简" : "显示全部";
            this.Button3.Text = this.btn_showAll.Text;
            div_listFrame.Style["padding-bottom"] = ShowAll ? "17px" : "0px";
            this.grd_list.Style["width"] = ShowAll ? "200%" : "100%";
            this.ShowColumns();
        }

        protected void grd_list_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                int id = this.GetInt(e.CommandArgument.ToString());
                Codification ett = new Codification();
                ett.GetProperties(id);
                if (e.CommandName == "downloadItem")
                {
                    this.StartDownload(ett);
                }
                else if (e.CommandName == "deleteItem")
                {
                    ett.Delete();
                }
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Codification ett = new Codification();
                    ett.GetProperties(((DataRowView)e.Row.DataItem).Row);
                    this.ShowSequenceNumber(e.Row, 1);
                    WebControl c = (WebControl)e.Row.FindControl("LinkButton2");
                    e.Row.Cells[3].Text = ett.Category.Name;
                    e.Row.Cells[6].Text = this.FormatDT(ett.ReleaseDT);
                    e.Row.Cells[7].Text = this.FormatDT(ett.ImplementDT);
                    e.Row.Cells[8].Text = this.FormatDT(ett.UploadDT);
                    e.Row.Cells[9].Text = ett.IsValid ? "是" : "否";

                    this.HighlightMulti(e.Row, 2, 4, 5, 10, 11, 12, 13);
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                g_pageInfo.PageIndex = e.NewPageIndex;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (g_pageInfo.Sort == e.SortExpression)
                {
                    g_pageInfo.Direction = !g_pageInfo.Direction;
                }
                else
                {
                    g_pageInfo.Direction = true;
                }
                g_pageInfo.Sort = e.SortExpression;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void tre_obj_SelectedNodeChanged(object sender, EventArgs e)
        {
            LastID = this.GetInt(this.tre_obj.SelectedValue);
            this.GetCondition();
            this.BindGrid();
        }
    }

}